import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { ArrowLeft, Save, X } from 'lucide-react'
import LoadingSpinner from '../components/LoadingSpinner'
import { apiRequest } from '../services/api'

interface RecurringTask {
  id: string
  title: string
  description?: string
  priority: string
  category: string
  tags: string[]
  notes?: string
  recurringType: 'daily' | 'weekly' | 'monthly' | 'yearly'
  recurringPattern: string | null
  isActive: boolean
}

export default function RecurringTaskEditPage() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [task, setTask] = useState<RecurringTask | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isSaving, setIsSaving] = useState(false)

  useEffect(() => {
    if (id) {
      loadTask()
    }
  }, [id])

  const loadTask = async () => {
    try {
      const taskData = await apiRequest<RecurringTask>(`/recurring/${id}`)
      setTask({
        ...taskData,
        tags: taskData.tags || [],
        description: taskData.description || '',
        notes: taskData.notes || ''
      })
    } catch (error) {
      console.error('加载任务失败:', error)
      alert('加载任务失败')
      navigate('/recurring')
    } finally {
      setIsLoading(false)
    }
  }

  const handleSave = async () => {
    if (!task || !task.title.trim()) {
      alert('任务标题不能为空')
      return
    }

    setIsSaving(true)
    try {
      await apiRequest(`/recurring/${id}`, {
        method: 'PUT',
        body: JSON.stringify({
          title: task.title,
          description: task.description,
          priority: task.priority,
          category: task.category,
          tags: task.tags,
          notes: task.notes,
          recurringType: task.recurringType,
          recurringPattern: task.recurringPattern
        })
      })

      navigate('/recurring')
    } catch (error) {
      console.error('保存任务失败:', error)
      alert('保存失败，请重试')
    } finally {
      setIsSaving(false)
    }
  }



  if (isLoading) {
    return (
      <div className="min-h-screen bg-theme-bg-secondary flex items-center justify-center">
        <LoadingSpinner />
      </div>
    )
  }

  if (!task) {
    return (
      <div className="min-h-screen bg-theme-bg-secondary flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-xl font-medium text-theme-text mb-2">任务不存在</h2>
          <button
            onClick={() => navigate('/recurring')}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            返回重复任务
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-theme-bg-secondary">
      {/* 顶部导航 */}
      <div className="sticky top-0 z-10 bg-theme-bg/95 backdrop-blur-sm border-b border-theme-border/60 shadow-sm">
        <div className="flex items-center justify-between px-4 sm:px-6 py-4">
          <button
            onClick={() => navigate('/recurring')}
            className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all"
          >
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-lg font-semibold text-theme-text">编辑重复任务</h1>
          <div className="flex items-center gap-2">
            <button
              onClick={() => navigate('/recurring')}
              className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all"
            >
              <X size={20} />
            </button>
            <button
              onClick={handleSave}
              disabled={isSaving}
              className="p-2 text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-lg transition-all disabled:opacity-50"
            >
              <Save size={20} />
            </button>
          </div>
        </div>
      </div>

      <div className="px-4 sm:px-6 pb-24 space-y-6 max-w-2xl mx-auto py-6">
        {/* 基本信息 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-6 shadow-sm">
          <h3 className="text-lg font-semibold text-theme-text mb-4">基本信息</h3>
          
          <div className="space-y-4">
            {/* 标题 */}
            <div>
              <label className="block text-sm font-medium text-theme-text mb-2">任务标题</label>
              <input
                type="text"
                value={task.title}
                onChange={(e) => setTask({ ...task, title: e.target.value })}
                className="w-full px-3 py-2 bg-theme-bg-secondary border border-theme-border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-theme-text"
                placeholder="输入任务标题..."
              />
            </div>

            {/* 描述 */}
            <div>
              <label className="block text-sm font-medium text-theme-text mb-2">描述</label>
              <textarea
                value={task.description}
                onChange={(e) => setTask({ ...task, description: e.target.value })}
                rows={3}
                className="w-full px-3 py-2 bg-theme-bg-secondary border border-theme-border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-theme-text resize-none"
                placeholder="输入任务描述..."
              />
            </div>

            {/* 优先级和分类 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-theme-text mb-2">优先级</label>
                <select
                  value={task.priority}
                  onChange={(e) => setTask({ ...task, priority: e.target.value })}
                  className="w-full px-3 py-2 bg-theme-bg-secondary border border-theme-border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-theme-text"
                >
                  <option value="P0">P0 - 紧急</option>
                  <option value="P1">P1 - 重要</option>
                  <option value="P2">P2 - 普通</option>
                  <option value="P3">P3 - 低优先级</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-theme-text mb-2">分类</label>
                <select
                  value={task.category}
                  onChange={(e) => setTask({ ...task, category: e.target.value })}
                  className="w-full px-3 py-2 bg-theme-bg-secondary border border-theme-border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-theme-text"
                >
                  <option value="work">工作</option>
                  <option value="personal">个人</option>
                  <option value="learning">学习</option>
                  <option value="health">健康</option>
                  <option value="other">其他</option>
                </select>
              </div>
            </div>

            {/* 标签 */}
            <div>
              <label className="block text-sm font-medium text-theme-text mb-2">标签</label>
              <input
                type="text"
                value={task.tags.join(', ')}
                onChange={(e) => setTask({ ...task, tags: e.target.value.split(',').map(tag => tag.trim()).filter(tag => tag) })}
                className="w-full px-3 py-2 bg-theme-bg-secondary border border-theme-border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-theme-text"
                placeholder="用逗号分隔多个标签..."
              />
            </div>
          </div>
        </div>

        {/* 重复设置 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-6 shadow-sm">
          <h3 className="text-lg font-semibold text-theme-text mb-4">重复设置</h3>
          
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-theme-text mb-2">重复类型</label>
                <select
                  value={task.recurringType}
                  onChange={(e) => setTask({ ...task, recurringType: e.target.value as any })}
                  className="w-full px-3 py-2 bg-theme-bg-secondary border border-theme-border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-theme-text"
                >
                  <option value="daily">每日</option>
                  <option value="weekly">每周</option>
                  <option value="monthly">每月</option>
                  <option value="yearly">每年</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-theme-text mb-2">状态</label>
                <div className="flex items-center gap-3 py-2">
                  <span className={`px-3 py-1 rounded-full text-sm font-medium ${
                    task.isActive 
                      ? 'bg-green-50 text-green-700 border border-green-200' 
                      : 'bg-gray-50 text-gray-700 border border-gray-200'
                  }`}>
                    {task.isActive ? '活跃' : '暂停'}
                  </span>
                </div>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-theme-text mb-2">重复模式</label>
                              <select
                  value={task.recurringPattern || ''}
                  onChange={(e) => setTask({ ...task, recurringPattern: e.target.value })}
                  className="w-full px-3 py-2 bg-theme-bg-secondary border border-theme-border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-theme-text"
                >
                  <option value="">请选择重复模式</option>
                  <optgroup label="每日">
                    <option value="every_day">每天</option>
                    <option value="every_weekday">每个工作日</option>
                    <option value="every_weekend">每个周末</option>
                    <option value="every_2_days">每两天</option>
                    <option value="every_3_days">每三天</option>
                  </optgroup>
                  <optgroup label="每周">
                    <option value="every_week">每周</option>
                    <option value="every_monday">每周一</option>
                    <option value="every_tuesday">每周二</option>
                    <option value="every_wednesday">每周三</option>
                    <option value="every_thursday">每周四</option>
                    <option value="every_friday">每周五</option>
                    <option value="every_saturday">每周六</option>
                    <option value="every_sunday">每周日</option>
                    <option value="every_2_weeks">每两周</option>
                  </optgroup>
                  <optgroup label="每月">
                    <option value="every_month">每月</option>
                    <option value="every_month_on_1st">每月1号</option>
                    <option value="every_month_on_15th">每月15号</option>
                    <option value="every_month_last_day">每月最后一天</option>
                    <option value="every_quarter">每季度</option>
                    <option value="every_6_months">每半年</option>
                  </optgroup>
                  <optgroup label="每年">
                    <option value="every_year">每年</option>
                  </optgroup>
                </select>
            </div>
          </div>
        </div>

        {/* 备注 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-6 shadow-sm">
          <h3 className="text-lg font-semibold text-theme-text mb-4">备注</h3>
          <textarea
            value={task.notes}
            onChange={(e) => setTask({ ...task, notes: e.target.value })}
            rows={4}
            className="w-full px-3 py-2 bg-theme-bg-secondary border border-theme-border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-theme-text resize-none"
            placeholder="输入备注信息..."
          />
        </div>
      </div>
    </div>
  )
}
